#include "channel.h"
#include "configs.h"


namespace BCHChannel {
  // for preventing the seed to be the same for each gsl    
  time_t gsl_seed = time(NULL) * rand();

  // construct one random number generator
  gsl_rng* get_one_rand_num_generator() {
    const gsl_rng_type * T;
    gsl_rng * r;                  
    /* create a generator chosen by the        
       environment variable GSL_RNG_TYPE */ 
    gsl_rng_env_setup();                                                                                
    gsl_rng_default_seed =  gsl_seed;                                                                    
    gsl_seed += rand(); // ok for PC, not for HPC: time(NULL) + N * clock() % K;                        
    sleep(0.2);                                                                                         
#ifdef VERBOSE                                                                                          
    cout << "seed of gsl:" << gsl_rng_default_seed << endl;                                             
#endif                                                                                                  
    T = gsl_rng_default;                                                                                
    r = gsl_rng_alloc (T);                                                                              
    return r;                                                                                           
  }

  // add bsc noise to the codeword
  void add_noise_bsc(vec_GF2& codeword){
    const double P[2] = {(1 - fliprate), fliprate};                                                     
    gsl_ran_discrete_t* x = gsl_ran_discrete_preproc(2, P);                                             
    gsl_rng* g = get_one_rand_num_generator();                                                          
    gsl_ran_discrete(g, x);                                                                             
    for(long i = 1; i <= codeword.length(); i++){ 
      if (gsl_ran_discrete(g, x) == 1)                                                                  
	codeword(i) += 1;                                                                               
    }                                                                                           
    delete g;                                                                                           
    gsl_ran_discrete_free(x);                                                                           
  }          
}
